<template>
  <div class="withdraw-management">
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2>提现管理</h2>
          <p>每月15号后可提现上个月及之前的收益部分</p>
        </div>
        <div class="header-right">
          <el-button
            icon="el-icon-refresh"
            @click="refreshAllData">
            刷新数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 账户概览 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :span="8">
        <el-card class="overview-card total-earnings">
          <div class="card-content">
            <div class="card-icon">
              <i class="el-icon-money"></i>
            </div>
            <div class="card-info">
              <div class="card-value">{{ formatAmount(accountInfo.totalEarnings) }}</div>
              <div class="card-label">累计收益</div>
            </div>
            <div class="income-types">
              <div class="income-type-item adincome-item" @click="goToCommissionDetail(1)">
                <div class="income-type-info">
                  <div class="income-type-title">广告收益</div>
                  <div class="income-type-value">{{ formatAmount(accountInfo.adincome) }}</div>
                </div>
              </div>
              <div class="income-type-item alliance-item" @click="goToCommissionDetail(2)">
                <div class="income-type-info">
                  <div class="income-type-title">异业联盟收益</div>
                  <div class="income-type-value">{{ formatAmount(accountInfo.alliancelncome) }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="overview-card withdrawable">
          <div class="card-content">
            <div class="card-icon">
              <i class="el-icon-wallet"></i>
            </div>
            <div class="card-info">
              <div class="card-value">{{ formatAmount(accountInfo.withdrawableAmount) }}</div>
              <div class="card-label">可提现金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="overview-card withdrawn">
          <div class="card-content">
            <div class="card-icon">
              <i class="el-icon-success"></i>
            </div>
            <div class="card-info">
              <div class="card-value">{{ formatAmount(accountInfo.withdrawnAmount) }}</div>
              <div class="card-label">已提现金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 提现申请 -->
    <el-card class="withdraw-card" v-if="canWithdraw">
      <div slot="header" class="card-header">
        <span>提现申请</span>
        <el-button type="primary" @click="showWithdrawDialog">申请提现</el-button>
      </div>

      <div class="withdraw-info">
        <el-alert
          title="提现说明"
          type="info"
          :closable="false">
          <p>• 每月15号后可提现上个月及之前的收益</p>
          <p>• 提现金额将通过支付宝转入您的支付宝账户</p>
          <p>• 提现申请提交后，将在1-3个工作日内处理</p>
          <p>• 单次提现金额不能低于100元</p>
        </el-alert>
      </div>
    </el-card>

    <!-- 不可提现提示 -->
    <el-card class="withdraw-card" v-else>
      <div class="no-withdraw-tip">
        <i class="el-icon-time tip-icon"></i>
        <h3>暂不可提现</h3>
        <p>每月15号后可提现上个月及之前的收益</p>
        <p>下次可提现时间：{{ nextWithdrawDate }}</p>
      </div>
    </el-card>

    <!-- 收益记录 -->
    <el-card class="earnings-card">
      <div slot="header" class="card-header">
        <span>收益记录</span>
        <div class="header-actions">
          <el-date-picker
            v-model="dateRange"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            @change="handleDateChange">
          </el-date-picker>
          <el-button type="primary" @click="loadEarningsRecords">查询</el-button>
        </div>
      </div>

      <configurable-table
        :columns="earningsColumns"
        :data="earningsRecords"
        :loading="loading"
        :show-index="false">
        <!-- 收益金额 -->
        <template slot="commissionAmount" slot-scope="{ row }">
          <span class="earnings-amount">{{ formatAmount(row.commissionAmount) }}</span>
        </template>
        <!-- 提现状态 -->
        <template slot="withdrawStatus" slot-scope="{ row }">
          <el-tag :type="getWithdrawStatusTag(row.withdrawStatus)">
            {{ getWithdrawStatusText(row.withdrawStatus) }}
          </el-tag>
        </template>
      </configurable-table>
    </el-card>

    <!-- 提现记录 -->
    <el-card class="withdraw-records-card">
      <div slot="header" class="card-header">
        <span>提现记录</span>
      </div>

      <configurable-table
        :columns="withdrawColumns"
        :data="withdrawRecords"
        :loading="loading"
        :show-pagination="true"
        :current-page.sync="withdrawPagination.current"
        :page-size.sync="withdrawPagination.size"
        :pagination-total="withdrawPagination.total"
        @page-change="handleWithdrawPageChange"
        :show-index="false">
        <!-- 提现金额 -->
        <template slot="amount" slot-scope="{ row }">
          <span class="withdraw-amount">{{ formatAmount(row.amount) }}</span>
        </template>
        <!-- 提现状态 -->
        <template slot="status" slot-scope="{ row }">
          <el-tag :type="getWithdrawRecordStatusTag(row.status)">
            {{ getWithdrawRecordStatusText(row.status) }}
          </el-tag>
        </template>
      </configurable-table>
    </el-card>

    <!-- 提现申请对话框 -->
    <el-dialog
      title="申请提现"
      :visible.sync="withdrawDialogVisible"
      width="500px"
      :close-on-click-modal="false">

      <el-form :model="withdrawForm" :rules="withdrawRules" ref="withdrawForm" label-width="120px">
        <el-form-item label="可提现金额">
          <span class="withdrawable-info">{{ formatAmount(accountInfo.withdrawableAmount) }}</span>
        </el-form-item>

        <el-form-item label="提现金额" prop="amount">
          <el-input-number
            v-model="withdrawForm.amount"
            :precision="2"
            :step="100"
            :min="100"
            :max="accountInfo.withdrawableAmount"
            style="width: 100%;">
          </el-input-number>
        </el-form-item>

        <el-form-item label="支付宝账户" prop="bankAccount">
          <el-input v-model="withdrawForm.bankAccount" placeholder="请输入支付宝账户（手机号或邮箱）"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="withdrawForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）">
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="withdrawDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitWithdraw" :loading="withdrawLoading">确认提现</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { submitAgentWithdraw } from '@/api/aggregation'
import request from '@/utils/request'
import ConfigurableTable from '@/components/ConfigurableTable/index.vue'
import { getIncomeStats } from '@/api/agent/withdraw'

export default {
  name: 'AgentWithdraw',
  components: {
    ConfigurableTable
  },
  data() {
    return {
      loading: false,
      withdrawLoading: false,
      accountInfo: {
        totalEarnings: 0,
        withdrawableAmount: 0,
        withdrawnAmount: 0,
        adincome: 0,        // 广告收益
        alliancelncome: 0   // 异业联盟收益
      },
      earningsRecords: [],
      withdrawRecords: [],
      dateRange: [],
      // 提现记录分页配置
      withdrawPagination: {
        current: 1,
        size: 10,
        total: 0
      },
      withdrawDialogVisible: false,
      withdrawForm: {
        amount: 100,
        bankAccount: '',
        remark: ''
      },
      withdrawRules: {
        amount: [
          { required: true, message: '请输入提现金额', trigger: 'blur' },
          { type: 'number', min: 100, message: '提现金额不能低于100元', trigger: 'blur' }
        ],
        bankAccount: [
          { required: true, message: '请输入支付宝账户信息', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    canWithdraw() {
      const now = new Date()
      const day = now.getDate()
      return day >= 15
    },
    nextWithdrawDate() {
      const now = new Date()
      const currentMonth = now.getMonth()
      const currentYear = now.getFullYear()
      return `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-15`
    },
    // 收益记录表格列配置
    earningsColumns() {
      return [
        { prop: 'month', label: '收益月份', minWidth: 120, align: 'center' },
        { prop: 'totalOrders', label: '订单数量', minWidth: 100, align: 'center' },
        {
          prop: 'totalAmount',
          label: '订单总金额',
          minWidth: 120,
          align: 'center',
          formatter: (row, column, cellValue) => this.formatAmount(cellValue || row.totalAmount)
        },
        {
          prop: 'commissionRate',
          label: '分佣比例',
          minWidth: 100,
          align: 'center',
          formatter: (row, column, cellValue) => `${((cellValue || row.commissionRate) * 100).toFixed(2)}%`
        },
        {
          prop: 'commissionAmount',
          label: '收益金额',
          minWidth: 120,
          align: 'center',
          slot: 'commissionAmount'
        },
        {
          prop: 'withdrawStatus',
          label: '提现状态',
          minWidth: 100,
          align: 'center',
          slot: 'withdrawStatus'
        },
        { prop: 'withdrawableDate', label: '可提现时间', minWidth: 120, align: 'center' }
      ]
    },
    // 提现记录表格列配置
    withdrawColumns() {
      return [
        { prop: 'withdrawNo', label: '提现单号', minWidth: 160 },
        {
          prop: 'amount',
          label: '提现金额',
          minWidth: 120,
          align: 'center',
          slot: 'amount'
        },
        { prop: 'bankAccount', label: '支付宝账户', minWidth: 200 },
        {
          prop: 'status',
          label: '提现状态',
          minWidth: 100,
          align: 'center',
          slot: 'status'
        },
        { prop: 'applyTime', label: '申请时间', minWidth: 160, align: 'center' },
        { prop: 'processTime', label: '处理时间', minWidth: 160, align: 'center' },
        { prop: 'remark', label: '备注', minWidth: 150 }
      ]
    }
  },
  mounted() {
    this.refreshAllData()
  },
  methods: {
    // 刷新所有数据
    async refreshAllData() {
      this.loading = true
      try {
        // 重置分页到第一页
        this.withdrawPagination.current = 1
        // 同时加载所有数据，确保数据一致性
        await Promise.all([
          this.loadWithdrawInfo(),
          this.loadEarningsRecords(),
          this.loadWithdrawRecords()
        ])
        this.$message.success('数据刷新成功')
      } catch (error) {
        Logger.error('刷新数据失败:', error)
        this.$message.error('刷新数据失败')
      } finally {
        this.loading = false
      }
    },
    // 提现申请API
    async submitWithdrawRequest(data) {
      return request({
        url: '/agg/withdraw/add',
        method: 'post',
        data: data
      })
    },

    // 获取提现列表API
    async getWithdrawList(params) {
      return request({
        url: '/agg/withdraw/page',
        method: 'post',
        data: params
      })
    },

    // 获取提现详情API
    async getWithdrawDetail(id) {
      return request({
        url: '/agg/withdraw/getInfo',
        method: 'get',
        params: { id: id }
      })
    },

    // 提现审核API（业务员通常不需要，但保留接口）
    async checkWithdraw(data) {
      return request({
        url: '/agg/withdraw/check',
        method: 'post',
        data: data
      })
    },

    // 加载提现信息
    async loadWithdrawInfo() {
      try {
        this.loading = true
        Logger.log('=== 加载通用收益统计 ===')

        // 只调用通用收益统计接口
        const incomeStatsResponse = await getIncomeStats().catch(error => {
          Logger.error('通用收益统计接口调用失败:', error)
          return { code: 500, data: {} }
        })

        Logger.log('提现管理 - 通用收益统计响应:', incomeStatsResponse)

        // 处理通用收益统计（广告收益、异业联盟收益）
        if (incomeStatsResponse.code === 0) {
          const incomeData = incomeStatsResponse.data

          this.accountInfo = {
            totalEarnings: incomeData.totalIncome || 0,  // 总收益
            withdrawableAmount: incomeData.availableAmount || 0,   // 可提现金额
            withdrawnAmount: incomeData.pendingAmount || 0,    // 已提现金额
            adincome: incomeData.adincome || 0,    // 广告收益
            alliancelncome: incomeData.alliancelncome || 0  // 异业联盟收益
          }
        } else {
          Logger.warn('通用收益统计接口返回错误:', incomeStatsResponse.data)
          this.accountInfo = {
            totalEarnings: 0,
            withdrawableAmount: 0,
            withdrawnAmount: 0,
            adincome: 0,
            alliancelncome: 0
          }
        }

        Logger.log('提现管理 - 映射后的账户信息:', this.accountInfo)
      } catch (error) {
        Logger.error('加载提现信息失败:', error)
        // 不设置模拟数据，保持默认值
        this.accountInfo = {
          totalEarnings: 0,
          withdrawableAmount: 0,
          withdrawnAmount: 0,
          adincome: 0,
          alliancelncome: 0
        }
      } finally {
        this.loading = false
      }
    },

    // 加载收益记录
    async loadEarningsRecords() {
      try {
        this.loading = true
        Logger.log('提现管理 - 加载收益记录（暂无接口，显示空数据）')

        // 暂时显示空数据，等后端收益记录接口可用后再接入
        this.earningsRecords = []

      } catch (error) {
        Logger.error('加载收益记录失败:', error)
        this.earningsRecords = []
      } finally {
        this.loading = false
      }
    },

    // 加载提现记录
    async loadWithdrawRecords() {
      try {
        this.loading = true
        Logger.log('提现管理 - 加载提现记录')

        const params = {
          pageNum: this.withdrawPagination.current,
          pageSize: this.withdrawPagination.size
        }

        const response = await this.getWithdrawList(params)
        Logger.log('提现管理 - 提现列表响应:', response)

        if (response.code === 200) {
          // 设置分页总数
          if (response.total !== undefined) {
            this.withdrawPagination.total = response.total
          }

          if (response.rows && response.rows.length > 0) {
            this.withdrawRecords = response.rows.map(item => ({
              withdrawNo: item.id || item.withdrawNo,
              amount: item.amount || 0,
              bankAccount: item.bankAccount || '支付宝账户',
              status: item.status || 1, // 1-待处理，2-已处理，3-已拒绝
              applyTime: item.createTime || item.applyTime,
              processTime: item.updateTime || item.processTime,
              remark: item.remark || '提现申请'
            }))

            Logger.log('提现管理 - 处理后的提现记录:', this.withdrawRecords)
          } else {
            this.withdrawRecords = []
          }
        } else {
          Logger.log('提现管理 - 暂无提现记录')
          this.withdrawRecords = []
          this.withdrawPagination.total = 0
        }

      } catch (error) {
        Logger.error('加载提现记录失败:', error)
        this.withdrawRecords = []
        this.withdrawPagination.total = 0
      } finally {
        this.loading = false
      }
    },

    // 提现记录分页变化处理
    handleWithdrawPageChange() {
      this.loadWithdrawRecords()
    },

    // 显示提现对话框
    showWithdrawDialog() {
      this.withdrawForm = {
        amount: Math.min(100, this.accountInfo.withdrawableAmount),
        bankAccount: '',
        remark: ''
      }
      this.withdrawDialogVisible = true
    },

    // 处理提现错误提示
    handleWithdrawError(error) {
      // 优先显示 detail 字段的详细信息
      if (error.detail) {
        this.$message.error(error.detail)
        return
      }
      // 其次显示 message 字段
      if (error.message) {
        this.$message.error(error.message)
        return
      }
      // 兼容旧格式的 msg 字段
      if (error.msg) {
        this.$message.error(error.msg)
        return
      }
      // 默认错误提示
      this.$message.error('提现申请失败，请重试')
    },

    // 提交提现申请
    async submitWithdraw() {
      try {
        await this.$refs.withdrawForm.validate()
        this.withdrawLoading = true

        const params = {
          amount: this.withdrawForm.amount * 100, // 转换为分
          bankAccount: this.withdrawForm.bankAccount,
          remark: this.withdrawForm.remark || '区域代理提现申请'
        }

        Logger.log('提现管理 - 提交提现申请:', params)

        const response = await this.submitWithdrawRequest(params)
        Logger.log('提现管理 - 提现申请响应:', response)

        if (response.code === 200) {
          this.$message.success('提现申请提交成功')
          this.withdrawDialogVisible = false
          this.loadWithdrawInfo()
          this.loadWithdrawRecords()
        } else {
          // 使用统一的错误处理函数
          this.handleWithdrawError(response)
        }
      } catch (error) {
        Logger.error('提交提现申请失败:', error)
        // 处理异常情况下的错误信息
        if (error.response && error.response.data) {
          this.handleWithdrawError(error.response.data)
        } else if (error.data) {
          this.handleWithdrawError(error.data)
        } else {
          this.$message.error('提现申请失败，请重试')
        }
      } finally {
        this.withdrawLoading = false
      }
    },

    // 日期范围改变
    handleDateChange(dateRange) {
      Logger.log('日期范围改变:', dateRange)
      this.loadEarningsRecords()
    },

    // 格式化金额
    formatAmount(amount) {
      if (typeof amount === 'number') {
        return '¥' + (amount / 100).toFixed(2)
      } else if (typeof amount === 'string') {
        return amount.startsWith('¥') ? amount : '¥' + amount
      }
      return '¥0.00'
    },

    // 跳转到收益详情页
    goToCommissionDetail(platform) {
      // platform: 1=广告收益, 2=异业联盟收益
      this.$router.push({
        name: 'AgentIncomeDetail',
        query: { incomeType: platform }
      })
    },

    // 获取提现状态标签
    getWithdrawStatusTag(status) {
      const statusMap = {
        1: 'success',  // 可提现
        2: 'info'      // 已提现
      }
      return statusMap[status] || 'default'
    },

    // 获取提现状态文本
    getWithdrawStatusText(status) {
      const statusMap = {
        1: '可提现',
        2: '已提现'
      }
      return statusMap[status] || '未知'
    },

    // 获取提现记录状态标签
    getWithdrawRecordStatusTag(status) {
      const statusMap = {
        1: 'warning',  // 待处理
        2: 'success',  // 已处理
        3: 'danger'    // 已拒绝
      }
      return statusMap[status] || 'default'
    },

    // 获取提现记录状态文本
    getWithdrawRecordStatusText(status) {
      const statusMap = {
        1: '待处理',
        2: '已处理',
        3: '已拒绝'
      }
      return statusMap[status] || '未知'
    }
  }
}
</script>

<style scoped>
.withdraw-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left {
  flex: 1;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right .el-button {
  background-color: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.3);
  color: white;
}

.header-right .el-button:hover {
  background-color: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  color: white;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  border-radius: 8px;
  overflow: hidden;
}

.overview-card.total-earnings {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.overview-card.withdrawable {
  background: linear-gradient(135deg, #56ab2f, #a8e6cf);
  color: white;
}

.overview-card.withdrawn {
  background: linear-gradient(135deg, #f093fb, #f5576c);
  color: white;
}

.overview-card.adincome-card {
  background: linear-gradient(135deg, #409eff, #66b1ff);
  color: white;
}

.overview-card.alliance-card {
  background: linear-gradient(135deg, #9c27b0, #ba68c8);
  color: white;
}

.card-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.total-earnings .card-content {
  justify-content: space-between;
}

.income-types {
  display: flex;
  flex-direction: row;
  gap: 24px;
  margin-left: 20px;
  padding-left: 20px;
  border-left: 1px solid rgba(255, 255, 255, 0.3);
}

.income-type-item {
  position: relative;
  padding: 6px 15px;
  padding-left: 48px;
  border-radius: 6px;
  background-color: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  transition: all 0.3s;
  cursor: pointer;
}

.income-type-item:hover {
  background-color: rgba(255, 255, 255, 0.25);
  transform: translateY(-1px);
}

.income-type-item::before {
  content: '';
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 32px;
  border-radius: 2px;
}

.adincome-item::before {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.7));
}

.alliance-item::before {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.7));
}

.income-type-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.income-type-title {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

.income-type-value {
  font-size: 18px;
  font-weight: 600;
  color: white;
}

.card-icon {
  font-size: 32px;
  margin-right: 15px;
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.card-label {
  font-size: 14px;
  opacity: 0.9;
}

.withdraw-card, .earnings-card, .withdraw-records-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.withdraw-info {
  margin-bottom: 20px;
}

.no-withdraw-tip {
  text-align: center;
  padding: 40px;
}

.tip-icon {
  font-size: 48px;
  color: #909399;
  margin-bottom: 20px;
}

.no-withdraw-tip h3 {
  margin: 0 0 10px 0;
  color: #606266;
}

.no-withdraw-tip p {
  margin: 5px 0;
  color: #909399;
}

.earnings-amount {
  color: #67c23a;
  font-weight: bold;
}

.withdraw-amount {
  color: #e6a23c;
  font-weight: bold;
}

.withdrawable-info {
  color: #67c23a;
  font-weight: bold;
  font-size: 16px;
}

.dialog-footer {
  text-align: right;
}
</style>
